#coding=utf-8
import json
import uuid
from django.http import HttpResponse
#另外还要导入用eval动态创建的对象所在的包

#urls.py里要注册这两个action,如下
#(r'^getobject$', 'xxx.index.getObject'),
#(r'^invoke$', 'xxx.index.invoke'),


def getObject(request):
    """返回一个对象的实例，需要name参数，表示对象的类名"""
    name = request.REQUEST.get('name', None)
    result = ""
    if not name:
        return mkErrorResponse(400, "need name parameter")
    else:
        guid = str(uuid.uuid1())
        try:
            request.session[guid] = eval(name + '()')
            result = json.dumps({"result": mkApiResponse(200, "ok"),
                "configid":guid} )
            return mkResponse(result) 
        except NameError:
            return mkErrorResponse(400, "name parameter invalid")

def invoke(request):
    """调用某实例的方法，guid是对象实例的存根，op是方法的操作"""
    guid = request.REQUEST.get('guid')
    if not guid:
        return mkErrorResponse(400,"guid")
    config = request.session.get(guid, None);
    if not config:
        return mkErrorResponse(404,"coonfig not found,expire or not init")
    op = request.REQUEST.get('op')
    if not op:
        return mkErrorResponse(400,"need op parameter")

    try:
        result = eval('config.'+ op)
        result = json.dumps({"result": mkApiResponse(200, "ok"),
            "data":result} )
        return mkResponse(result) 
    except:
        return mkErrorResponse(500, "invoke error")


def mkApiResponse(code, message):
    return {"code":code, "message":message}

def mkErrorResponse(code, message):
    result = json.dumps({"result": mkApiResponse(code, message)})
    return mkResponse(result) 

def mkResponse(result):
    response = HttpResponse(mimetype="text/plain") #也可以用application/json
    response.write(result)
    return response


